﻿using UnityEngine;
using System.Collections;

public class cakeScript : MonoBehaviour 
{
	
	private float				timeStamp; 
	private float				cakeInterval = 15f;
	private int					cakeLayers = 0;
	private ScoreManager		scoreMNG;
	
	//POISON
	public bool					isPoisoned = false; 
	public int					poisonRadius;
	
	private Transform			myTransform;
	private Collider			myCollider; 
	private stateScript			gameState;
	
	
	void Start () 
	{
		timeStamp = Time.time + cakeInterval; 
		
		myTransform = transform; 
		gameState = (stateScript)FindObjectOfType (typeof(stateScript)); 
		scoreMNG = (ScoreManager)FindObjectOfType (typeof(ScoreManager)); 
		
		myCollider = collider;

		UpdateShowLayer ();
	}
	
	
	void Update () 
	{
		if (Time.time > timeStamp) 
		{
			timeStamp = Time.time + cakeInterval;
			
			//Enlarge cake
			CakeGrow();
		}
		
		if (cakeLayers > 3) 
		{
			ShareCake();
			gameState.RoundOver();
		}
		
	}

	public void CakeGrow ()
	{
		Debug.Log (cakeLayers +=1);	
		//All sheeppathers. there is cake!

		if (cakeLayers > 0) 
		{
			SheepPather[] pathers = FindObjectsOfType( typeof(SheepPather) ) as SheepPather[];
			foreach(SheepPather sp in pathers)
			{
				sp.ThereIsCake(transform.position);
			}
			
		}
		UpdateShowLayer ();
	}

	private void UpdateShowLayer( )
	{
		for (int i = 0; i < transform.childCount; ++i) 
		{
			transform.GetChild(i).gameObject.SetActive(false);
		}
		Transform child = transform.Find ("Layer" + cakeLayers);
		if (child) 
		{
			child.gameObject.SetActive(true);
		}
	}
	
	public void CakeEat ()
	{
		cakeLayers -= 1;
		cakeLayers = Mathf.Max (cakeLayers, 0);
		if (cakeLayers <= 0) 
		{
			SheepPather[] pathers = FindObjectsOfType( typeof(SheepPather) ) as SheepPather[];
			foreach(SheepPather sp in pathers)
			{
				sp.NoCake(transform.position);
			}

		}
		UpdateShowLayer ();
	}
	
	public void PoisonCake(Vector2 eaterPos)
	{
		if( Vector2.Distance( eaterPos, this.transform.position) < poisonRadius )
		{
			isPoisoned = true;
		}

//		Debug.Log ("POISONED CAKE!!");
	}
	
	void ShareCake ()
	{
		scoreMNG.ShareCake ();
	}
	
	
	void OnTriggerEnter(Collider col)
	{
		ScoreScript score = col.GetComponent<ScoreScript> ();
		
		//player enters
		if(score) 
		{
			if(isPoisoned == false)
			{
				scoreMNG.EatAllCake(score.playerNumber); 
				gameState.RoundOver(); 
			}
			else
			{
				scoreMNG.EatPoison(score.playerNumber);
				gameState.RoundOver(); 
			}


		}
		
		//sheep enters

		CakeStealer stealer = col.GetComponent<CakeStealer> ();
		if (stealer) 
		{

			if(cakeLayers >= 1)
			{
				CakeEat ();
				Destroy (stealer.gameObject);
			}
			else
			{
				CakeEat ();

			}

		}
		
		
	}
	
}

